﻿using System;
using System.Collections.Generic;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Practices.Composite.Events;
using Silverlight.Weblog.Client.DAL.Services;
using Silverlight.Weblog.Common.IoC;
using Silverlight.Weblog.Server.DAL;
using Silverlight.Weblog.Shared.Common.Exception;
using Silverlight.Weblog.Shared.Common.Helpers;

namespace Silverlight.Weblog.Client.DAL.Events
{
    /// <summary>
    /// Converts Hyperlink clicks to Prism Composition events.
    /// 3 rules on the hyperlink must apply:
    /// 1) Set the Targetname to a HyperlinkToPrismEvent control
    /// 2) Set the NavigateUrl to the name of the class event
    /// 3) set the datacontext of HyperlinkToPrismEvent to the event payload
    /// 4) If a NavigateUrl is specfied as "Foo#Bar" the payload becomes the DataContext.Bar
    /// </summary>
    public class HyperlinkToPrismEvent : FrameworkElement, INavigate
    {
        #region Implementation of INavigate

        private static Dictionary<string, Type> SourceStartWithAndEvent = 
            new Dictionary<string, Type>()
              {
                {"NavigateToHomePageEvent", typeof(NavigateToHomePageEvent)},
                {"GoToBlogPostPermlinkEvent", typeof(GoToBlogPostPermlinkEvent)},
                {"GoToBlogPostEvent", typeof(GoToBlogPostEvent)},
                {"DisplayCategory", typeof(DisplayCategoryEvent)},
              };

        public bool Navigate(Uri source)
        {
            foreach (KeyValuePair<string, Type> pair in SourceStartWithAndEvent)
            {
                 if (source.OriginalString.StartsWith(pair.Key + "#"))
                     return RaiseEvent(source, pair.Key + "#", pair.Value);
            }
            return false;
        }

        private bool RaiseEvent(Uri Source, string StartsWith, Type EventType)
        {

            string propertyNameToGetBlogPost = Source.OriginalString.Replace(StartsWith, string.Empty);
            object propertyValue = this.DataContext.GetProperty(propertyNameToGetBlogPost);
            IoC.Get<IEventAggregator>().InvokeGeneric("GetEvent", EventType).Invoke("Publish", propertyValue);
            return true;
        }

        #endregion
    }
}
